package com.utils
{
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.ui.Mouse;
	
	public class Drag
	{
		private static var drag:Drag;
		private var _target:MovieClip;
		private var _contain:MovieClip;
		
		public function Drag()
		{
			if(drag){
				throw Error('DragUtil--->不能重复实例化!')
			}else{
				drag = this;
			}
		}
		
		public static function get instance():Drag{
			if(!drag) drag = new Drag();
			return drag;
		}
		
		public function addTarget(target:DisplayObjectContainer,targetContain:DisplayObjectContainer):void{
			_target = target as MovieClip;
			_contain = targetContain as MovieClip;
			_target.addEventListener(MouseEvent.MOUSE_DOWN,onDragHandler);
			_target.addEventListener(Event.REMOVED_FROM_STAGE,onRemoveFromStageHandler);
		}
		
		private function onDragHandler(e:MouseEvent):void
		{
			if(e.currentTarget == _target && e.type == MouseEvent.MOUSE_DOWN){
				_contain.stage.addEventListener(MouseEvent.MOUSE_UP,onDragHandler);
				_contain.stage.addEventListener(Event.ENTER_FRAME,onEnterFrameHandler);
				_contain.startDrag();
			}else if(e.type == MouseEvent.MOUSE_UP){
				_contain.stage.removeEventListener(MouseEvent.MOUSE_UP,onDragHandler);
				_contain.stage.removeEventListener(Event.ENTER_FRAME,onEnterFrameHandler);
				_contain.stopDrag();
				onEnterFrameHandler();
			}
		}
		
		private function onEnterFrameHandler(e:Event= null):void
		{
			if(_contain.x + _contain.width >= _contain.stage.stageWidth){
				_contain.x = _contain.stage.stageWidth - _contain.width;
			}else if(_contain.x <= 0){
				_contain.x = 0;
			}
			if(_contain.y + _contain.height >= _contain.stage.stageHeight){
				_contain.y = _contain.stage.stageHeight - _contain.height;
			}else if(_contain.y <= 0){
				_contain.y = 0;
			}
			
		}
		
		private function onRemoveFromStageHandler(e:Event=null):void
		{
			_target.removeEventListener(MouseEvent.MOUSE_DOWN,onDragHandler);
			_target.removeEventListener(Event.REMOVED_FROM_STAGE,onRemoveFromStageHandler);
			trace('移除拖拽!')
		}
		
		
	}
}